import React, { PureComponent } from 'react';
import { connect } from 'react-redux';

import { Layout, Breadcrumb, Icon } from 'antd';
import {
    Form,
    ButtonEvent,
    Modal,
    Tip
} from '../../../components';
import { mainService } from '../../../service';
import { cmsNewAction as actionCreates, mainAction } from '../../../store/action';

import "./add.less";

//移动窗口位置
window.moveTo(10,10);

class Index extends PureComponent{
    constructor(props){
        super(props);

        this.state = {
            apiname:'cms/article',
            formLeftData : [],
            formRightData : [],

            dragvisible:false,
        }
    }
    render(){
        const { cates, posts } = this.props;
        const { formLeftData, formRightData, dragvisible } = this.state;
        let ndata1=formLeftData;
        let ndata2=formRightData;
        
		ndata1.map((item)=>{
			if(item["name"]==="cid"){
				item["treeData"]=cates;
			}
			if(item["name"]==="post_id"){
				item["options"]=posts.map((it)=>{
					return {name:it["name"],value:it["id"]}
				});
			}
			return item;
		})

        return(
            <div className="article_bg">
                <Layout.Content className="article_con">
                    <Breadcrumb className="breadcrumb">
                        <Breadcrumb.Item>
                            <Icon type="file-text" style={{color:"#1890ff"}} />
                            <span>内容管理</span>
                        </Breadcrumb.Item>
                        <Breadcrumb.Item>
                            <span>文章管理</span>
                        </Breadcrumb.Item>
                        <Breadcrumb.Item>
                            添加文章
                        </Breadcrumb.Item>
                    </Breadcrumb>
                    <div layout = 'inline' className="art_addBox clearfix">
                        <Layout.Content className="art_l">
                            <Form
                                layout = 'horizontal'
                                data = {ndata1}
                                wrappedComponentRef={(form) => this.formLeftRef = form}
                            />
                        </Layout.Content>
                        <Layout.Content className="art_r">
                            <Form
                                layout = 'vertical'
                                data = {ndata2}
                                wrappedComponentRef={(form) => this.formRightRef = form}
                            />
                        </Layout.Content>
                    </div>
                </Layout.Content>
                <div
                    style={{
                        position: 'fixed',
                        bottom: 0,
                        zIndex:999,
                        width: '100%',
                        borderTop: '1px solid #e8e8e8',
                        padding: '10px 16px',
                        textAlign: 'center',
                        left: 0,
                        background: '#fff',
                        borderRadius: '0 0 4px 4px',
                    }}
                >
                    <ButtonEvent data={ [
                        {key:0,type:'primary',value:'保存并关闭',btnloading:"1",onClick:()=>{
                            this.save();
                        }}
                        ,{key:1,value:'关闭',onClick:()=>{
                            this.closeWindow();
                        }}
                        ,{key:2,value:'预览',onClick:()=>{
                            this.preview()
                        }}
                    ]} />
                </div>
                
                <Modal
                    visible={ dragvisible }
                    title = "预览"
                    maskClosable={true}
                    destroyOnClose={true}
                    onCancel={this.handleCancel}
                    footer={null}
                    width="375px"
                    style={{
                        top:10
                    }}
                    drag={true}
                    className="preview"
                >
                </Modal>
            </div>
        )
    }

    //保存数据
    save = async ()=>{
        const {apiname} = this.state;

        let valueLeft = await this.formLeftRef.getItemsValue();
        let valueRight = await this.formRightRef.getItemsValue();
        if(valueLeft && valueRight){
            this.changeBtnLoading(true);
            let values = Object.assign({}, valueLeft);
            values = Object.assign(values, valueRight);
            try{
                let res = await mainService.crud(apiname+"/add",values);
                this.tipMsg(res);
            }catch{
                this.tipMsg({code:3,msg:"网络错误"});
            }
        }
        setTimeout(()=>{
            this.changeBtnLoading(false);
        },500);
    }
    //消息提示
    tipMsg = (res,type='')=>{
        if(res.code===0){
            Tip.Message(res.msg+"关闭页面中......",'success');
            setTimeout(() => {
                this.closeWindow();
            }, 1500);
        }else{
            Tip.Message(res.msg,'error')
        }
    }

    getCates = async ()=>{
        const { apiname } = this.state;
		const { bindCates, bindPost } = this.props;
		let cid = 0;
		if(this.props.match.params.cid!==undefined){
            cid=this.props.match.params.cid;
        }
		//获取栏目和推荐位
        let res = await mainService.getlist(apiname+'/getcate?cid='+cid);
		bindCates(res);
		bindPost(res);
    }

    initForm = ()=>{
        const { formLeft, formRight } = this.props;
        //初始化添加的form表单数据
        let cid = 0;
        if(this.props.match.params.cid!==undefined){
            cid=this.props.match.params.cid;
        }
        let formLeftArr=[];
        for(let i=0;i<formLeft['arr'].length;i++){
            let v = formLeft['arr'][i];
            let o = {};
            o = Object.assign({},formLeft[v]);
            if(formLeft['arr'][i]==="cid"){
                o.value = cid;
			}
            formLeftArr.push(o)
        }
        // for (let i in formLeft) {
        //     let o = {};
        //     o = Object.assign({},formLeft[i]);
        //     if(i==="cid"){
        //         o.value = cid;
        //     }
        //     if(i==="content"){
        //         o.extendControls=[
        //             {
        //                 key: 'custom-button',
        //                 type: 'button',
        //                 text: '预览',
        //                 onClick: this.preview
        //             }
        //         ]
        //     }
        //     formLeftArr.push(o)
        // }

        
        let formRightArr=[];
        for(let i=0;i<formRight['arr'].length;i++){
            let v = formRight['arr'][i];
            let o = {};
            o = Object.assign({},formRight[v]);
            formRightArr.push(o)
        }
        this.setState({
            formLeftData:formLeftArr,
            formRightData:formRightArr
        });
    }
    componentDidMount(){
        this.getCates();
        this.initForm();
    }
    //保存按钮状态
    changeBtnLoading = (bool)=>{
        this.props.bindBtnLoading(bool)
    }

    closeWindow = ()=>{
        if (navigator.userAgent.indexOf("MSIE") > 0) {     
            if (navigator.userAgent.indexOf("MSIE 6.0") > 0) {     
                window.opener = null; window.close();     
            }else{     
                window.open('', '_top'); window.top.close();     
            }     
        } else if (navigator.userAgent.indexOf("Firefox") > 0) {     
            window.location.href = 'about:blank '; //火狐默认状态非window.open的页面window.close是无效的    
            //window.history.go(-2);     
        } else {     
            window.opener = null;      
            window.open('', '_self', '');     
            window.close();     
        }
    }

    //预览
    preview = () => {
        this.setState({
            dragvisible:true
        })
    }
    //关闭预览
    handleCancel=()=>{
        this.setState({
            dragvisible:false
        })
    }
}

const mapStateToProps = (state)=>{

    const name = 'cms_new';
    const cates = state.getIn([name,'cates']).toJS();
    const defcateid = state.getIn([name,'defcateid']).toJS();
    const posts = state.getIn([name,'posts']).toJS();
    const defpostid = state.getIn([name,'defpostid']).toJS();
    const formLeft = state.getIn([name,'formLeft']).toJS();
    const formRight = state.getIn([name,'formRight']).toJS();

    const btnloading = state.getIn(['main','btnloading']);

    return{
        cates,
        defcateid,
        posts,
        defpostid,
        formLeft,
        formRight,

        btnloading
    }
}
const mapDispatchToProps = (dispatch)=>{
    return{
        bindCates(res){
            if(res.code === 0){
                dispatch(actionCreates.setCates(res.data,res.arrid));
            }
        },
        bindPost(res){
            if(res.code === 0){
                dispatch(actionCreates.setPost(res.posts,res.postid));
            }
        },
        bindBtnLoading(bool){
            dispatch(mainAction.setBtnLoading(bool));
        }
    }
}

export default connect(mapStateToProps,mapDispatchToProps)(Index);